package com.dbq.fast.business.product;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IntRange;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.FireBaseUserPurchaseTrack;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.h5.H5ContainerActivity;
import com.dbq.fast.business.login.NewLoginActivity;
import com.dbq.fast.business.login.bean.CustomProfile;
import com.dbq.fast.business.login.business.LoginBiz;
import com.dbq.fast.business.main.MainActivity;
import com.dbq.fast.business.order.OrderListActivity;
import com.dbq.fast.business.product.adapter.ViewPagerAdapter;
import com.dbq.fast.business.product.api.EventApi;
import com.dbq.fast.business.product.api.ProductApi;
import com.dbq.fast.business.product.bean.ProductType;
import com.dbq.fast.business.product.bean.ServiceType;
import com.dbq.fast.business.product.dialog.PayAndLoginStatusDialog;
import com.dbq.fast.business.product.event.FaceBookUserPurchaseTrack;
import com.dbq.fast.business.product.fragment.FixedSpeedScroller;
import com.dbq.fast.business.product.fragment.ProductFragment;
import com.dbq.fast.business.product.ui.CustomViewPager;
import com.dbq.fast.business.product.ui.PayChooseItem;
import com.dbq.fast.business.product.ui.StatusView;
import com.dbq.fast.common.base.BaseActivity;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.json.GsonT;
import com.dbq.fast.common.manager.DatabaseManager;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.util.ProgressDialogUtil;
import com.facebook.CallbackManager;
import com.yiba.sa.pay.StripeAliPay;
import com.yiba.vpn.utils.Constants;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.dbq.fast.analysis.EventConstant.SLIP_TO_S1;
import static com.dbq.fast.analysis.EventConstant.SLIP_TO_S2;
import static com.dbq.fast.business.h5.H5ContainerActivity.IS_HELP;


public class ProductTypeActivity extends BaseActivity {

    @BindView(R.id.viewPager)
    CustomViewPager customViewPager;

    @BindView(R.id.choose_pay)
    PayChooseItem choosePay;

    @BindView(R.id.amount)
    TextView amountTv;

    @BindView(R.id.btn_pay)
    Button payBtn;

    @BindView(R.id.title_tv)
    TextView titleTv;

    @BindView(R.id.status_view)
    StatusView statusView;

    @BindView(R.id.tv_payment)
    TextView paymentTv;
    @BindView(R.id.tv_set_meal_status)
    TextView setMealStatus;
    @BindView(R.id.tv_other_pay_info)
    TextView otherPayInfoTv;

    @BindView(R.id.tv_according_to_holy)
    TextView accordingToHoly;

    private ServiceType.AppServiceListBean chooseServiceExtra;

    private int CURRENT_DIALOG_STATUS = 0000;
    private ProductType.SetMealListBean checkProduct = null;

    //使用dialog处理支付状态时，显示dialog时机的问题。房子dialog出错。
    private boolean isShowPayStatusDialog = false;

    private FixedSpeedScroller mScroller;

    //ali支付的状态码
    private static final int ALI_PAY = 6;
    public static final int REWARD_CLOSE = 4;
    //用于在切换支付方式时，记录选中的条目
    private int SELECT_PAY_TYPE = PayChooseItem.GOOGLE_PAY;

    private int buyStatus = 0; //0 表示购买失败，1 表示

    public static Handler handler;
    private ViewPagerAdapter viewPagerAdapter;
    private List<ProductFragment> fragments;
    private StripeAliPay stripeAliPay;
    private HashMap<String, String> map = new HashMap<>();
    List<ServiceType.AppServiceListBean> rootData;

    int tag = 0; //该字段用于记录用户连续点击了多少次，当点击超过15次时，上传为测试用户的时间

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_type);
        ButterKnife.bind(this);
        initHandler();
        initEvent();
        initLogicStatus();
        initStripeAli();
        initAdapter();
        initListener();
        loadServiceData();
        saveEvent(EventConstant.CLICK_PLAN, "");
    }

    /**
     * 初始化stripe和alipay支付的对象。
     */
    private void initStripeAli() {
        stripeAliPay = new StripeAliPay(this, Constants.STRIPE_ID);
    }


    private void loadServiceData() {
        setWidgetVisible(View.GONE);
        ProductApi.questService(new RemoteApiCallBack<List<ServiceType.AppServiceListBean>>() {
            @Override
            public void onSuccess(List<ServiceType.AppServiceListBean> listBeans) {
                loadServiceType(listBeans);

            }

            @Override
            public void onFail(int status, String message) {
                loadServiceDataFailed(status, message);
            }
        });
    }

    private void loadServiceDataFailed(int status, String message) {
        if (status == 402) {
            Toast.makeText(App.getContext(), message, Toast.LENGTH_SHORT).show();
            if (isFinishing()) return;
            if (Build.VERSION.SDK_INT >= 17 && isDestroyed()) return;
        } else if (status == 426) {
            statusView.setStatus(StatusView.SERVICE_ERROR);
        } else {
            statusView.setStatus(StatusView.NET_ERROR);
        }
        saveEvent(EventConstant.LOAD_PAYPAGE_FAILED, "1");
    }

    /**
     * 在第一个接口加载服务类型数据成功后，处理相关逻辑
     *
     * @param listBeans
     */
    private void loadServiceType(List<ServiceType.AppServiceListBean> listBeans) {
        fragments.clear();
        rootData = listBeans;
        for (int i = listBeans.size() - 1; i > -1; i--) {
            chooseServiceExtra = listBeans.get(i);
            initUiData();
            //TODO 选中一个商品
            ProductFragment p0 = new ProductFragment()
                    .addParam("extra", chooseServiceExtra)
                    .build();
            p0.setOnCheckedListener(new ProductOnCheckItemListener(i));
            p0.setOnLoadListener(new OnLoadStatus());
            fragments.add(p0);
        }
        viewPagerAdapter.notifyDataSetChanged();
    }


    private class OnLoadStatus implements ProductFragment.OnLoadStatusListener {

        @Override
        public void onStartLoad() {
            if (fragments.get(0).getLoadStatus()) {
                statusView.setStatus(StatusView.LOADING);
                setWidgetVisible(View.GONE);
            }
        }

        @Override
        public void onLoadError() {
            if (fragments.get(0).getLoadStatus()) {
                statusView.setStatus(StatusView.NET_ERROR);
                setWidgetVisible(View.GONE);
                saveEvent(EventConstant.LOAD_PAYPAGE_FAILED, "2");

            }

        }

        @Override
        public void onLoadComplete() {

            if (fragments.get(0).getLoadStatus()) {
                statusView.setStatus(StatusView.SUCCESS);
                setWidgetVisible(View.VISIBLE);
                saveEvent(EventConstant.LOAD_PAYPAGE_SUCCESS, "");
            }
        }
    }

    private void setWidgetVisible(int visible) {
        choosePay.setVisibility(visible);
        paymentTv.setVisibility(visible);
    }


    private class ProductOnCheckItemListener implements ProductFragment.OnCheckItemListener {
        private int index = 0;

        public ProductOnCheckItemListener(int index) {
            this.index = index;
        }

        @Override
        public void onChecked(ProductType.SetMealListBean data) {
            checkProduct = data;
            //在item点击切换过程中，修改选中的值。
            bindData();
            if (data != null) {
                saveEvent(EventConstant.CLICK_ITEM, data.googleId);
            }
        }
    }

    public void bindData() {
        if (checkProduct != null) {
            if (checkProduct.isInvalid) {
                //不允许购买时，修改界面中的元素为不可购买状态
                isAllowBuy(checkProduct.isInvalid, "0", getFormatTime(checkProduct.setMealDeadLine));
            } else {
                isAllowBuy(false, checkProduct.setMealDiscountRmbPrice, getFormatTime(checkProduct.setMealDeadLine));
            }
        }
    }


    /**
     * 初始化，选择支付方式的事件名
     */
    private void initEvent() {
        map.put("4", EventConstant.STRIPE_METHOD);
        map.put("3", EventConstant.GOOGLE_METHOD);
        map.put("5", EventConstant.WFEE_METHOD);
    }


    /**
     * 改变界面的状态值
     */
    private void initLogicStatus() {
        accordingToHoly.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        choosePay.selectPayType(PayChooseItem.STRIPE_PAY);
        statusView.setStatus(StatusView.LOADING);
    }


    private void initAdapter() {
        fragments = new ArrayList<>();
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragments);
        customViewPager.setAdapter(viewPagerAdapter);
        customViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //y用于左右切换的过程中，改变当前的数据
                checkProduct = fragments.get(position).getCheckedData();
                if (checkProduct != null) {
//                Log.i("tag", "onPageSelected = " + checkProduct.googleId);
                    saveEvent("switch_page_" + position, checkProduct.googleId);
                }
                bindData();
                if (position == 0) {
                    position = 1;
                    YibaAnalysis.getInstance().event(App.getContext(), SLIP_TO_S2);
                } else {
                    position = 0;
                    YibaAnalysis.getInstance().event(App.getContext(), SLIP_TO_S1);
                }
                fragments.get(position).notifyCloseItem();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        try {
            // 通过class文件获取mScroller属性
            Field mField = ViewPager.class.getDeclaredField("mScroller");
            mField.setAccessible(true);

            mScroller = new FixedSpeedScroller(customViewPager.getContext(), new AccelerateInterpolator());
            mField.set(customViewPager, mScroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void initUiData() {
        titleTv.setText(getResources().getString(R.string.Purchase));
        int availableTime = User.getInstance().getUserSetMealAvailableTime();
        String availableTimeDesc = availableTime + "";
        if (availableTime == -1) {
            setMealStatus.setText(getResources().getString(R.string.account_no_set_meal));
        } else if (availableTime == 1) { // 蔡芳说的，在购买套餐时，不足一天的显示一天。12月29日
            availableTimeDesc = "<1";
            availableTimeDesc += getResources().getString(R.string.day);
            setMealStatus.setText(availableTime == 0 ? getResources().getString(R.string.account_no_set_meal) : getResources().getString(R.string.account_set_meal) + User.getInstance().getUserServiceName() + getResources().getString(R.string.residue) + availableTimeDesc);
        } else {
            availableTimeDesc += getResources().getString(R.string.day);
            setMealStatus.setText(availableTime == 0 ? getResources().getString(R.string.account_no_set_meal) : getResources().getString(R.string.account_set_meal) + User.getInstance().getUserServiceName() + getResources().getString(R.string.residue) + availableTimeDesc);
        }
    }

    private void setExpireTime(boolean boo, String str) {
        SpannableStringBuilder style = new SpannableStringBuilder(str);
        style.setSpan(new ForegroundColorSpan(this.getResources().getColor(R.color.pay_btn_purple)), boo ? str.length() : str.length() - 10, str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        otherPayInfoTv.setText(style);
    }

    /**
     * 转换时间
     *
     * @param time
     * @return
     */
    private String getFormatTime(String time) {
        Date date = new Date(Long.valueOf(time) * 1000);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    private void initHandler() {
        handler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case REWARD_CLOSE:
                        if (!ProductTypeActivity.this.isFinishing()) {
                            Intent intent = new Intent(ProductTypeActivity.this, MainActivity.class);
                            startActivity(intent);
                            onBackPressed();
                        }
                        break;
                    case ALI_PAY:
                        stripePayResultLogic();
                        break;
                }
            }
        };
    }


    private void stripePayResultLogic() {
        if (isResume) {
            bindDialogListener();
            PayAndLoginStatusDialog.show(getSupportFragmentManager(), CURRENT_DIALOG_STATUS);
        } else {
            isShowPayStatusDialog = true;
        }
    }


    private void initListener() {
        choosePay.setOnSelectItemListener(id -> {
            SELECT_PAY_TYPE = id;
            paySwitchEvent(SELECT_PAY_TYPE);
        });

        statusView.setViewVisibleListener(visible -> setWidgetVisible(visible));
        statusView.setRefreshListener(() -> {
            statusView.setStatus(StatusView.LOADING);
            saveEvent(EventConstant.CLICK_RELOAD_DATA_PAYPAGE, "");
            loadServiceData();
        });

        bindDialogListener();


    }

    private void bindDialogListener() {
        //设置支付状态的dialog回调
        PayAndLoginStatusDialog.setBottomBtn(new PayAndLoginStatusDialog.OnBottomBtnListener() {
            @Override
            public void continuePay() {
                stripeAliPay.continuePay();
                saveEvent(EventConstant.POP_PAY_CANCEL, "");

            }

            @Override
            public void goMainPage() {
                Intent intent = new Intent(ProductTypeActivity.this, MainActivity.class);
                startActivity(intent);
                onBackPressed();
            }

            @Override
            public void goOrderPage() {
                Intent intent = new Intent(ProductTypeActivity.this, OrderListActivity.class);
                startActivity(intent);
                onBackPressed();
            }

            @Override
            public void goLoginPage() {
                jumpToLogin("");
            }

            @Override
            public void cancel() {
                saveEvent(EventConstant.CLICK_COMFIRM__PAY_CANCEL, "");
            }
        });
        PayAndLoginStatusDialog.setOnCountDown(() -> {
            Intent intent = new Intent(ProductTypeActivity.this, MainActivity.class);
            startActivity(intent);
            onBackPressed();
        });

    }

    private void sendMsg2DD(String type, String status, int resultCode, String result) {
        EventApi.send2DdEvent(type, status, resultCode, result, String.valueOf(chooseServiceExtra.serviceLevel), checkProduct);
    }

    private void payFailedStatus(int code) {
        Bundle bundle = new Bundle();
        bundle.putString("status", String.valueOf(code));
        YibaAnalysis.getInstance().event(App.getContext(), EventConstant.PAYMENT_STATUS, bundle);
    }


    private void loaEvent(int index) {
        YibaAnalysis.getInstance().event(App.getContext(), "click_s" + chooseServiceExtra.serviceLevel + "_m" + getTag(index));//EventConstant.click_s1_m1);
        FaceBookUserPurchaseTrack.logEvent("click_s" + chooseServiceExtra.serviceLevel + "_m" + getTag(index));
    }

    /**
     * 通过index计算出当前的
     *
     * @param index
     * @return
     */
    private int getTag(int index) {
        if (index == 0) {
            return 1;
        } else {
            return 3 << (index - 1);
        }
    }

    /**
     * 跳转到登陆接卖弄
     *
     * @param message
     */
    private void jumpToLogin(String message) {
        if (!"".equals(message)) {
            Toast.makeText(App.getContext(), "" + message, Toast.LENGTH_SHORT).show();
        }
        if (isFinishing()) return;
        if (Build.VERSION.SDK_INT >= 17 && isDestroyed()) return;
        LoginBiz loginBiz = new LoginBiz(ProductTypeActivity.this);
        loginBiz.logOut();
        Intent intent = new Intent(this, NewLoginActivity.class);
        intent.putExtra("goLogin", true);
        startActivityForResult(intent, 1000);
    }

    /**
     * 显示支付金额
     *
     * @param dols 显示美元字段
     */
    private void showAmount(String dols) {
        amountTv.setText("¥" + dols);

    }

    @OnClick({R.id.back, R.id.btn_pay, R.id.tv_other_pay_info, R.id.tv_payment, R.id.tv_according_to_holy})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                onBackPressed();
                break;
            case R.id.btn_pay:
                if (SELECT_PAY_TYPE == PayChooseItem.GOOGLE_PAY) {//选择google支付
                    alipayDialog(checkProduct.hkdPrice);
                }
                clickPayBtn();
                break;
            case R.id.tv_other_pay_info:
            case R.id.tv_according_to_holy:
                // 点击跳转到链接页面
                Intent intent = new Intent(this, H5ContainerActivity.class);
                intent.putExtra("which", IS_HELP);
                startActivity(intent);
                break;
            case R.id.tv_payment:
                tag += 1;
                if (tag > 15) {
                    saveEvent(EventConstant.TEST_USER, "");
                }
                break;
        }
    }

    private class PayStatus implements StripeAliPay.OnPayStatusListener {
        @Override
        public void start() {
            if (isResume) {
                ProgressDialogUtil.showProgress(ProductTypeActivity.this, "", "");
            }
        }

        @Override
        public void stripeError(String s) {
            if (isResume) {
                ProgressDialogUtil.hideProgress();
            }
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.STRIPE_GET_TOKEN_FAILED);
            if (checkProduct != null) {
                saveEvent(EventConstant.STRIPE_GET_TOKEN_FAILED, s);
            }
        }

        @Override
        public void complete() {
            if (isResume) {
                ProgressDialogUtil.hideProgress();
            }
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.STRIPE_GET_TOKEN_SUCCESS);
            if (checkProduct != null) {
                saveEvent(EventConstant.STRIPE_GET_TOKEN_SUCCESS, "");
            }
        }

        @Override
        public void aliPayFaile(int i) {
            alipayErr(String.valueOf(i));
            sendMsg2DD("ali", "success", i, "");
        }

        @Override
        public void aliPaySuccess(String s) {
            stripeInvokePay(s);
            boolean isInstallAli = checkAliPayInstalled(ProductTypeActivity.this);
            CURRENT_DIALOG_STATUS = PayAndLoginStatusDialog.SUCCESS;
            bindDialogListener();
            if (isInstallAli && isResume) {
                PayAndLoginStatusDialog.show(getSupportFragmentManager(), CURRENT_DIALOG_STATUS);
            } else {
                isShowPayStatusDialog = true;
            }
            sendMsg2DD("ali", "ali_sdk_success", 2000, "");
            saveEvent(EventConstant.ALI_PAY_SUCCESS, "");
        }


    }

    private void alipayErr(String resultStatus) {
        boolean isInstallAli = checkAliPayInstalled(ProductTypeActivity.this);
        bindDialogListener();
        if (TextUtils.equals(resultStatus, "4000")) {
            CURRENT_DIALOG_STATUS = PayAndLoginStatusDialog.FAILED;
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.pay_failed_4000);
            if (isInstallAli && isResume) {
                PayAndLoginStatusDialog.show(getSupportFragmentManager(), CURRENT_DIALOG_STATUS);
            } else {
                isShowPayStatusDialog = true;
            }
            saveEvent(EventConstant.ALI_PAY_FAILED, EventConstant.pay_failed_4000);
        } else if (TextUtils.equals(resultStatus, "6002")) {
            saveEvent(EventConstant.ALI_PAY_FAILED, EventConstant.pay_failed_6002);
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.pay_failed_6002);
            CURRENT_DIALOG_STATUS = PayAndLoginStatusDialog.NET_ERROR;
            if (isInstallAli && isResume) {
                PayAndLoginStatusDialog.show(getSupportFragmentManager(), CURRENT_DIALOG_STATUS);
            } else {
                isShowPayStatusDialog = true;
            }

        } else if (TextUtils.equals(resultStatus, "6000") || TextUtils.equals(resultStatus, "8004")) {
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.pay_failed_8004);
            saveEvent(EventConstant.ALI_PAY_FAILED, EventConstant.pay_failed_8004);
            CURRENT_DIALOG_STATUS = PayAndLoginStatusDialog.UNDERWAR;
            if (isInstallAli && isResume) {
                PayAndLoginStatusDialog.show(getSupportFragmentManager(), CURRENT_DIALOG_STATUS);
            } else {
                isShowPayStatusDialog = true;
            }
        } else if (TextUtils.equals(resultStatus, "6001")) {
            CURRENT_DIALOG_STATUS = PayAndLoginStatusDialog.CANCEL;
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.pay_faild_cancel);
            saveEvent(EventConstant.ALI_PAY_FAILED, EventConstant.pay_faild_cancel);
        }
        handler.sendEmptyMessage(ALI_PAY);
    }

    /**
     * 判断当前设备是否安装支付宝应用
     *
     * @param context
     * @return
     */
    private static boolean checkAliPayInstalled(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }

    /**
     * 根据后台返回的支付金额，生成对应的支付钥匙串和用户后台进行确认扣款第二步需要的钥匙串。
     */
    private void alipayDialog(@IntRange(from = 0L) final long amount) {
        stripeAliPay.pay(amount, "hkd", String.valueOf(User.getInstance().getVpnId()), "product@pegasus-mobile.com", "http://www.pegasus-mobile.com/index_en.html", new PayStatus());
    }

    /**
     * 该方式用于在移动端调用支付宝支付成功以后，将source id 交给后台，后台用于调用stripe后台代码，实现扣款的第二部。如果后台不使用该sourceId调用，
     * 那么alipay支付的这笔钱将会退还给用户。
     *
     * @param payToken
     */
    private void stripeInvokePay(String payToken) {
        ProductApi.stripePay(this, checkProduct, payToken, new RemoteApiCallBack() {
            @Override
            public void onFail(int status, String message) {
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_STRIPE_PAY_FAILED);
                if (checkProduct != null) {
                    saveEvent(EventConstant.SERVICE_PAY_FAILED, message);
                }
            }

            @Override
            public void onSuccess(Object o) {
                paySuccessEvent();
            }
        });
    }

    /**
     * 显示支付状态的dialog，隐藏加载中的Dialog.
     *
     * @param status
     */
    private void showPayStatusDialogAndHideProgress(int status) {
        isShowPayStatusDialog = true;
        CURRENT_DIALOG_STATUS = status;
        if (isResume) {
            ProgressDialogUtil.hideProgress();
        }
    }

    /**
     * 支付成功时，使用facebook和firbase的统计data。
     * TODO
     */
    private void paySuccessEvent() {
        FaceBookUserPurchaseTrack.paySuccess(BigDecimal.valueOf(Double.parseDouble(checkProduct.setMealDiscountRmbPrice)), Currency.getInstance("CNY"));
        //购买成功
        if (checkProduct != null) {
            try {
                FireBaseUserPurchaseTrack.paySuccess(App.getContext(), BigDecimal.valueOf(Double.parseDouble(checkProduct.setMealDiscountRmbPrice)), getPayMethodName());
            } catch (Exception e) {

            }
        }

        CustomProfile profile = DatabaseManager.getInstance().queryProfile();
        profile.setUserServiceLevel(chooseServiceExtra.serviceLevel);
        DatabaseManager.getInstance().saveProfile(profile);

        Bundle bundle = new Bundle();
        bundle.putString(getPayResultEvent(), getPayMethodName());
        YibaAnalysis.getInstance().event(App.getContext(), getPayResultEvent(), bundle);
        if (checkProduct != null) {
            saveEvent(EventConstant.SERVICE_PAY_SUCCESS, checkProduct.googleId);
        }
    }


    private String getPayResultEvent() {
        return EventConstant.PAY_SUCCESS + "_s" + chooseServiceExtra.serviceLevel;
    }

    private String getPayMethodName() {
        if (SELECT_PAY_TYPE == PayChooseItem.GOOGLE_PAY) {//选择google支付
            return "google";
        } else if (SELECT_PAY_TYPE == PayChooseItem.STRIPE_PAY) { //选择stripe支付
            return "stripe";
        } else if (SELECT_PAY_TYPE == PayChooseItem.WFEE_PAY) {
            return "wfee";
        } else {
            return "other";
        }
    }

    /**
     * 支付成功时，使用facebook和firbase的统计data。
     */
    private void paySwitchEvent(int payMethod) {

        FaceBookUserPurchaseTrack.logEvent(map.get(String.valueOf(payMethod)));
        //购买成功
        YibaAnalysis.getInstance().event(App.getContext(), map.get(String.valueOf(payMethod)));
        if (checkProduct != null) {
            saveEvent(map.get(String.valueOf(payMethod)), checkProduct.googleId);
        }
    }


    /**
     * 点击支付按钮时金额统计,使用facebook和firbase的统计data。
     */
    private void clickPayBtn() {
        Bundle bundle = new Bundle();
        bundle.putString(getClickPayBtnEvent(), getPayMethodName());
        YibaAnalysis.getInstance().event(App.getContext(), getClickPayBtnEvent(), bundle);

        HashMap<String, String> hm = new HashMap<>();
        hm.put("id", String.valueOf(checkProduct.setMealId));
        hm.put("quantity", "1");
        hm.put("item_price", checkProduct.setMealDiscountRmbPrice);
        ArrayList al = new ArrayList<>();
        al.add(hm);
        String s = GsonT.toJson(al);
        FaceBookUserPurchaseTrack.initCheckout(chooseServiceExtra.serviceName, s);

        FireBaseUserPurchaseTrack.clickPlay(App.getContext(), BigDecimal.valueOf(Double.parseDouble(checkProduct.setMealDiscountRmbPrice)), getPayMethodName());
        saveEvent(EventConstant.CLICL_PAY_BUTTON, s);
    }


    private String getClickPayBtnEvent() {
        return EventConstant.click_pay_button + "_s" + chooseServiceExtra.serviceLevel;
    }


    /**
     * * 该方法处理是否能够购买
     *
     * @param boo  支付按钮是否可以点击
     * @param dols 美元
     */
    private void isAllowBuy(boolean boo, String dols, String time) {
        setExpireTime(boo, boo ? getResources().getString(R.string.no_per_buy) : getResources().getString(R.string.buy_time) + time);
        choosePay.setIsAllowPay(!boo);
        showAmount(dols);
        payBtn.setEnabled(!boo);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        CallbackManager callbackManager = CallbackManager.Factory.create();
        callbackManager.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000 && resultCode == 1001) {
            showPayStatusDialogAndHideProgress(PayAndLoginStatusDialog.ACCOUNT_ON_OTHER_DEVICES_LOGIN);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //处理第三方支付启动了Activity时，返回后在界面中弹出Dialog出现的异常。
        if (isShowPayStatusDialog) {
            isShowPayStatusDialog = false;
            bindDialogListener();
            PayAndLoginStatusDialog.show(getSupportFragmentManager(), CURRENT_DIALOG_STATUS);
        }
    }


    @Override
    synchronized protected void onDestroy() {
        handler = null;
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        saveEvent(EventConstant.EXIT_PAY_PAGE, "");
        YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_EXIT_PAYMENT_PAGE);
        setResult(buyStatus == 0 ? 1000 : 2000);
        ProductTypeActivity.this.finish();
    }

    private void saveEvent(String type, String segment) {
        EventApi.saveEvent(this, type, segment, chooseServiceExtra);
    }


}
